<template>
  <section>
    <div class="flex select-no-type">
      <div v-show="num === 0"
           class="row w150">
        <div v-if="form.trackType">
          <i :class="
              form.trackType === 1
                ? 'iconfont icon-dianzihuidan orange'
                : 'iconfont icon-kuaididanhao orange'
            "></i>
        </div>
        <el-select v-model="form.trackType"
                   placeholder="请选择跟踪方式"
                   @change="changeTrackType">
          <el-option v-for="item in trackTypeList"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value">
            <div>
              <i :class="
                  item.value === 1
                    ? 'iconfont icon-dianzihuidan'
                    : 'iconfont icon-kuaididanhao'
                "
                 style="margin-right: 5px"></i>{{ item.label }}
            </div>
          </el-option>
        </el-select>
      </div>
      <template v-if="form.trackType === 1">
        <div :class="flag ? 'oneDevice row' : 'otherDevice row'">
          <div class="deviceSty">{{ device }}</div>
          <el-select ref="deviceSelect"
                     v-model="form[deviceCodeList[num]]"
                     filterable
                     remote
                     :clearable="clearable"
                     placeholder="请输入编号后七位"
                     :remote-method="remoteMethod"
                     class="selectSty"
                     @keyup.enter.native="changeMateCode"
                     @blur="handleBlur"
                     @focus="handleFocus"
                     @change="changeCode"
                     @clear="deviceVer(form.trackType, form[deviceCodeList[num]])">
            <el-option v-for="item in codeList"
                       :key="item"
                       :label="item"
                       :value="item"></el-option>
          </el-select>
        </div>
      </template>
      <div v-else
           class="courierSty">
        <el-input v-model="form.deviceCode"
                  size="medium"
                  :placeholder="
            form.trackType === 1
              ? '请输入编号后七位'
              : form.trackType === 2
              ? '请输入快递单号'
              : '请选择编号类型'
          "
                  onkeyup="this.value=this.value.replace(/[^\w]/g,'')"
                  style="width: 300px"
                  :maxlength="form.trackType === 1 ? 7 : 25"
                  :minlength="form.trackType === 2 ? 7 : ''"
                  @input="deviceChange" />
      </div>
      <equipment-information v-if="form.trackType === 1 && form[deviceCodeList[num]]"
                             :battery-electric="deviceInfo.lithium"
                             :battery-electric-value="deviceInfo.lithiumValue"
                             :equipment-type="deviceInfo.type"
                             :equipment-status="deviceInfo.status" />
    </div>
  </section>
</template>

<script>
import EquipmentInformation from "./EquipmentInformation.vue";
import { order } from "@/api/index";
import { mapState } from "vuex";
export default {
  name: "SelectDevice",
  components: { EquipmentInformation },
  props: {
    formInfo: {
      type: Object,
      default: () => { }
    },
    devideNumber: [String, Number],
    process: Number,
    num: {
      type: Number,
      default: 0
    },
    flag: {
      type: Boolean,
      default: () => false
    }
  },
  computed: {
    ...mapState({
      // tenantId: (state) => state.login.tenantId
    }),
    user () {
      return JSON.parse(this.userInfo)
    }
  },
  data () {
    return {
      userInfo: sessionStorage.getItem('userInfo'),
      form: {},
      device: 35160808,
      deviceCodeList: ["deviceCode", "secondDeviceCode", "thirdDeviceCode"],
      trackTypeList: [
        {
          value: 1,
          label: "电子回单"
        },
        {
          value: 2,
          label: "快递单号"
        }
      ],
      codeList: [],
      // userInfo: this.$storage.read("LOGIN::userInfo"),
      inputCode: "",
      page: 1,
      deviceInfo: {},
      clearable: false
    };
  },
  created () {
    this.form = this.formInfo;
    this.clearable = this.num === 0 ? true : false;
  },
  mounted () {
    if (this.form.trackType === 1) this.getCodeList();
    this.showDevice();
  },
  methods: {
    deviceVer () {
      this.form[this.deviceCodeList[this.num]] = null;
      if (this.num === 0) {
        this.form.checkValue = null;
      }
      this.$forceUpdate();
    },
    remoteMethod (query) {
      this.inputCode = query;
      if (query.length > 2) this.getCodeList();
    },
    handleBlur () {
      if (this.inputCode.length >= 3 && this.codeList.length) {
        const code = this.codeList[0]
        let result = code.substring(code.length - 7);
        this.form[this.deviceCodeList[this.num]] = result;
        this.$refs.deviceSelect.blur();
        this.showDevice();
      }
      // this.inputCode = "";
      // this.getCodeList();
    },
    handleFocus () {
      this.inputCode = "";
      this.getCodeList();
    },
    async getCodeList () {
      let { code, data } = await order.deviceApi(
        this.page,
        100,
        `${this.device}${this.inputCode}`
      );
      if (code !== 0 || !data) return;
      this.codeList =
        data?.records && data?.records.length > 0 ? [...data.records] : [];
    },
    changeMateCode () {
      if (this.codeList.length < 2) {
        this.$nextTick(() => {
          const code = this.codeList[0]
          let result = code.substring(code.length - 7);
          this.form[this.deviceCodeList[this.num]] = result
          this.$refs.deviceSelect.blur()
        })
      }
    },
    changeTrackType (type) {
      if (!type) return;
      this.form.trackType = type;
      this.$emit("input", null, 1, this.form.trackType);
      this.$forceUpdate();
      this.form.deviceCode = null;
      this.form.checkValue = type === 2 ? null : this.form.checkValue;
    },
    changeCode (code) {
      if (!code) return;
      this.form[this.deviceCodeList[this.num]] = code.substring(8, code.length);
      this.$emit(
        "input",
        this.form[this.deviceCodeList[this.num]],
        this.process
      );
      this.$forceUpdate();
      this.showDevice();
    },
    async showDevice () {
      if (!this.form[this.deviceCodeList[this.num]]) return false;
      let { code, data } = await order.showDeviceApi(
        `${this.device}${this.form[this.deviceCodeList[this.num]]}`
      );
      if (code !== 0 || !data) return;
      this.deviceInfo = data;
      console.log("+======>deviceInfo", this.deviceInfo)
      // humidity 湿度   temperature 温度
      this.$emit('getReply', this.deviceInfo?.humidity, this.deviceInfo?.temperature)
      if (data?.lithium < 79) {
        this.$message.warning("请确保设备充满电，以免影响轨迹或是其他功能");
      }
    },
    initCode () {
      this.codeList = [];
      this.page = 1;
    },
    deviceChange (val) {
      this.form.deviceCode = val;
      this.$forceUpdate();
    }
  }
};
</script>

<style lang="scss" scoped>
.select-no-type {
  .device {
    text-align: center;
    width: 25%;
    height: 30px;
    line-height: 32px;
    display: block;
    border: none;
    background: #ccc2c23d;
  }
}
.row {
  display: flex;
  border: 1px solid #dcdfe6;
  height: 38px;
  padding: 0 10px;
  border-radius: 4px;
}
.w150 {
  width: 150px;
}
.oneDevice {
  width: 280px;
  margin-left: 10px;
}
.otherDevice {
  width: 280px;
}
.mr5 {
  margin-right: 5px;
}
.deviceSty {
  margin-right: 10px;
  line-height: 40px;
  width: 90px;
}
.orange {
  color: var(--prev-icon-color-orange);
}
.courierSty {
  position: relative;
  margin-left: 10px;
}
/deep/ .el-select .el-input__inner {
  border: hidden !important;
  margin-top: 2px;
}
</style>
